﻿namespace Harness.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Windows.Forms;

    internal class WaitCommand : ICommand
    {
        #region Constants

        private const int SleepTime = 500;

        #endregion

        #region Public Methods

        public void SyntaxCheck(IHarness harness, IEnumerable<object> args)
        {
            Verification.SyntaxCheck(harness, args);
        }

        public dynamic Execute(IHarness harness, IEnumerable<object> args)
        {
            DateTime startTime = DateTime.Now;

            while (Verification.IsFalse(harness, args))
            {
                DateTime nowTime = DateTime.Now;
                double seconds = (nowTime - startTime).TotalSeconds;

                if (harness.TimeoutSeconds < seconds)
                {
                    string msg = string.Format(
                        Properties.Resources.Exception_Timeout,
                        args.ElementAtOrDefault(0) ?? string.Empty);

                    throw new InvalidOperationException(msg);
                }

                Thread.Sleep(SleepTime);
                Application.DoEvents();
            }

            return null;
        }

        #endregion
    }
}
